import SvgCanvas from '../../svgcanvas/svgcanvas.js'
import { jGraduate,mkElem,setAttrs } from '../components/jgraduate/jQuery.jGraduate.js'
import BottomPanelHtml from './BottomPanel.html'
import { getSelectorManager, Selector, init as selectInit } from '../../svgcanvas/select.js'
import Paint from '../components/jgraduate/paint.js'

const { $id,$ } = SvgCanvas

/*
 * register actions for left panel
 */
/**
  * @type {module}
*/
class BottomPanel {
  /**
   * @param {PlainObject} editor svgedit handler
  */
  constructor (editor) {
    this.editor = editor
    this.selectorManager = getSelectorManager()
  }

  /**
   * @type {module}
   */
  get selectedElement () {
    return this.editor.selectedElement
  }

  /**
     * @type {module}
     */
  get multiselected () {
    return this.editor.multiselected
  }



  /**
    * @type {module}
    */
  changeStrokeWidth (e) {
    let val = e.target.value
    if (val === 0 && this.editor.selectedElement && ['line', 'polyline'].includes(this.editor.selectedElement.nodeName)) {
      val = 1
    }
    this.editor.svgCanvas.setStrokeWidth(val)
  }

  /**
    * @type {module}
    */
  changeZoom (value) {
    switch (value) {
      case 'canvas':
      case 'selection':
      case 'layer':
      case 'content':
        this.editor.zoomChanged(window, value)
        break
      default:
      {
        const zoomlevel = Number(value) > 0.1 ? Number(value) * 0.01 : 0.1
        const zoom = this.editor.svgCanvas.getZoom()
        const { workarea } = this.editor
        this.editor.zoomChanged(window, {
          width: 0,
          height: 0,
          // center pt of scroll position
          x: (workarea.scrollLeft + parseFloat(getComputedStyle(workarea, null).width.replace('px', '')) / 2) / zoom,
          y: (workarea.scrollTop + parseFloat(getComputedStyle(workarea, null).height.replace('px', '')) / 2) / zoom,
          zoom: zoomlevel
        }, true)
      }
    }
  }

  /**
     * @fires module:svgcanvas.SvgCanvas#event:ext_toolButtonStateUpdate
     * @returns {void}
     */
  updateToolButtonState () {
    const bNoFill = (this.editor.svgCanvas.getColor('fill') === 'none')
    const bNoStroke = (this.editor.svgCanvas.getColor('stroke') === 'none')
    const buttonsNeedingStroke = ['tool_fhpath', 'tool_line']
    const buttonsNeedingFillAndStroke = [
      // 'tools_rect', 'tools_ellipse',
      'tool_text', 'tool_path'
    ]

    if (bNoStroke) {
      buttonsNeedingStroke.forEach((btn) => {
        // if btn is pressed, change to select button
        if ($id(btn).pressed) {
          this.editor.leftPanel.clickSelect()
        }
        $id(btn).disabled = true
      })
    } else {
      buttonsNeedingStroke.forEach((btn) => {
        $id(btn).disabled = false
      })
    }
    if (bNoStroke && bNoFill) {
      buttonsNeedingFillAndStroke.forEach((btn) => {
        // if btn is pressed, change to select button
        if ($id(btn).pressed) {
          this.editor.leftPanel.clickSelect()
        }
        $id(btn).disabled = true
      })
    } else {
      buttonsNeedingFillAndStroke.forEach((btn) => {
        $id(btn).disabled = false
      })
    }
    this.editor.svgCanvas.runExtensions(
      'toolButtonStateUpdate',
      /** @type {module:svgcanvas.SvgCanvas#event:ext_toolButtonStateUpdate} */ {
        nofill: bNoFill,
        nostroke: bNoStroke
      }
    )
  }

  getPaint(lgType,color_,url){
    let html = "";
    const color = "#" + color_
    var paint_use = new Paint()
    if(url){
      var defs = $(url)
      paint_use.type = defs[0].tagName
      paint_use[paint_use.type] = defs[0]
      if(paint_use.type == "pattern"){
        this.solidColor = $(url).find("path").attr("stroke").substring(1)
        var paint = this.getPaint("solidColor",this.solidColor)
        this.editor.svgCanvas.setPaint("fill", paint)
      }
      return paint_use
    }
    switch(lgType){
      case "line_style":
        html = `<svg><defs><linearGradient x1="0" x2="0.2" y1="0.2" y2="0.8">
        <stop offset="0" stop-color="${color}" stop-opacity=1></stop>
        <stop offset="0.5" stop-color="${color}" stop-opacity=0.5></stop>
        <stop offset="1" stop-color="${color}" stop-opacity=1></stop></linearGradient></defs></svg>`
        break
      case "vert_style":
        html = `<svg><defs><pattern patternUnits="userSpaceOnUse" width="3" height="3">
        <path class="vert_style" d="M 3, 0 l 0, 3" stroke-width="1" shape-rendering="crispEdges" stroke="${color}" stroke-linecap="square"></path>
        </pattern></defs></svg>`
        break
      case "hori_style":
        html= `<svg><defs><pattern patternUnits="userSpaceOnUse" width="3" height="3">
        <path class="hori_style" d="M 0, 3 l 3, 0" stroke-width="1" shape-rendering="crispEdges" stroke="${color}" stroke-linecap="square"></path>
        </pattern></defs></svg>`
        break
      case "solidColor":
        html = "solidColor"
        break
    }
    var tmp = $(html)


    if(html == "" || html == "solidColor"){
      paint_use.type = 'solidColor'
      paint_use.solidColor = color_
      paint_use.alpha = (html == "")?0:100
    }else{
      var defs = tmp.find("defs>*")
      paint_use.type = defs[0].tagName
      paint_use[paint_use.type] = defs[0]
    }
    this.lgType = lgType
    return paint_use
  }

  getUrlFromAttr = function (attrVal) {
    if (attrVal) {
      // url('#somegrad')
      if (attrVal.startsWith('url("')) {
        return attrVal.substring(5, attrVal.indexOf('"', 6))
      }
      // url('#somegrad')
      if (attrVal.startsWith("url('")) {
        return attrVal.substring(5, attrVal.indexOf("'", 6))
      }
      if (attrVal.startsWith('url(')) {
        return attrVal.substring(4, attrVal.indexOf(')'))
      }
    }
    return null
  }

  /**
    * @type {module}
    */
  handleColorPicker (type, evt,isCube,position) {
    const selectedElements = this.editor.svgCanvas.getSelectedElements();
    if(type == "fill_style"){
      if(evt.detail.type=="fill_style"){
        var fill = evt.detail.fill
        var paint_use = null
        if(fill == null) return
        if(fill.indexOf("url")>-1){
           fill = this.getUrlFromAttr(fill)
           paint_use = this.getPaint(evt.detail.value,fill,fill)
        }else{
          fill = fill.replace("#","")
          var paint_use = this.getPaint(evt.detail.value,fill)
        }

        this.editor.svgCanvas.setPaint("fill", paint_use)
        this.editor.svgCanvas.fill_style = "fill_" + evt.detail.value
        return
      }
      var color = this.solidColor?this.solidColor:"ff0000"
      var paint_use = this.getPaint(evt.detail.value,color)
      this.editor.svgCanvas.setPaint("fill", paint_use)
      const len = selectedElements.length
      for (let i = 0; i < len; ++i) {
        const elem = selectedElements[i]
        if (elem) {
         var cls = elem.classList
         var clsLength = cls.length
         while(clsLength--){
          if(cls[clsLength].indexOf("fill_")>-1){
            cls.remove(cls[clsLength])
          }
         }
         cls.add("fill_" + evt.detail.value)
        }
      }
      this.editor.svgCanvas.fill_style = "fill_" + evt.detail.value
      return
    }

    var { paint } = evt.detail
    if(paint.type =="solidColor" && type == "fill"){
      this.solidColor = paint.solidColor
      paint = this.getPaint(this.lgType,this.solidColor)
    }
    this.editor.svgCanvas.setPaint(type, paint,isCube)
    this.updateToolButtonState()
  }

  /**
    * @type {module}
    */
  handleStrokeAttr (type, evt) {
    this.editor.svgCanvas.setStrokeAttr(type, evt.detail.value)
  }

  /**
    * @type {module}
    */
  handleOpacity (evt) {
    const val = Number.parseInt(evt.currentTarget.value.split('%')[0])
    this.editor.svgCanvas.setOpacity(val / 100)
  }

  /**
  * @type {module}
  */
  handlePalette (e) {
    e.preventDefault()
    // shift key or right click for stroke
    const { picker, color } = e.detail
    // Webkit-based browsers returned 'initial' here for no stroke
    const paint = color === 'none' ? new jGraduate.Paint() : new jGraduate.Paint({ alpha: 100, solidColor: color.substr(1) })
    if (picker === 'fill') {
      $id('fill_color').setPaint(paint)
    } else {
      $id('stroke_color').setPaint(paint)
    }
    this.editor.svgCanvas.setColor(picker, color)
    if (color !== 'none' && this.editor.svgCanvas.getPaintOpacity(picker) !== 1) {
      this.editor.svgCanvas.setPaintOpacity(picker, 1.0)
    }
    this.updateToolButtonState()
  }

  /**
  * @type {module}
  */
  init () {
    // register actions for Bottom panel
    const template = document.createElement('template')
    const { i18next } = this.editor
    template.innerHTML = BottomPanelHtml
    const a = this.editor.$svgEditor.querySelector('.tool_align_relativeWrap');
    const b = this.editor.$svgEditor.querySelector('.angleItemWrap')
    this.editor.$svgEditor.querySelector('#sidepanels .layerColor').append(template.content.cloneNode(true))
    this.editor.$svgEditor.querySelector('#sidepanels .layerColor #tools_bottom').append(a)
    this.editor.$svgEditor.querySelector('#sidepanels .layerColor #tools_bottom').append(b)
    const { curConfig } = this.editor.configObj
    $id('fill_color').setPaint(new jGraduate.Paint({ alpha: 100, solidColor: curConfig.initFill.color }))
    // $id('fill_color_front').setPaint(new jGraduate.Paint({ alpha: 100, solidColor: curConfig.initFill.color }))
    // $id('fill_color_left').setPaint(new jGraduate.Paint({ alpha: 100, solidColor: curConfig.initFill.color }))
    $id('stroke_color').setPaint(new jGraduate.Paint({ alpha: 100, solidColor: curConfig.initStroke.color }))
    $id('zoom').addEventListener('change', (e) => this.changeZoom.bind(this)(e.detail.value))
    $id('stroke_color').addEventListener('change', (evt) => this.handleColorPicker.bind(this)('stroke', evt))
    $id('fill_color').addEventListener('change', (evt) => this.handleColorPicker.bind(this)('fill', evt))
    // $id('fill_color_front').addEventListener('change', (evt) => this.handleColorPicker.bind(this)('fill', evt,true,'front'))
    // $id('fill_color_left').addEventListener('change', (evt) => this.handleColorPicker.bind(this)('fill', evt,true,'left'))
    // $id('fill_color_top').addEventListener('change', (evt) => this.handleColorPicker.bind(this)('fill', evt,true,'top'))
    $id('stroke_width').addEventListener('change', this.changeStrokeWidth.bind(this))
    $id('stroke_style').addEventListener('change', (evt) => this.handleStrokeAttr.bind(this)('stroke-dasharray', evt))
    $id('stroke_linejoin').addEventListener('change', (evt) => this.handleStrokeAttr.bind(this)('stroke-linejoin', evt))
    $id('fill_style').addEventListener('change', (evt) => this.handleColorPicker.bind(this)('fill_style', evt))

    $id('stroke_linecap').addEventListener('change', (evt) => this.handleStrokeAttr.bind(this)('stroke-linecap', evt))
    $id('opacity').addEventListener('change', this.handleOpacity.bind(this))
    $id('fill_color').init(i18next)
    // $id('fill_color_front').init(i18next)
    // $id('fill_color_left').init(i18next)
    // $id('fill_color_top').init(i18next)
    $id('stroke_color').init(i18next)
  }

  /**
  * @type {module}
  */
  updateColorpickers (apply) {
    $id('fill_color').update(this.editor.svgCanvas, this.editor.selectedElement, apply)
    $id('stroke_color').update(this.editor.svgCanvas, this.editor.selectedElement, apply)
  }
}

export default BottomPanel
